package com.mililoan.console.tools;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.mililoan.common.constant.RightmrgGlobe;
import com.mililoan.model.system.User;


/**
 * Class Name: WebUtil Description: TODO.
 * 
 * @author SC
 * 
 */
public final class WebUtil {
	@SuppressWarnings("unused")
	private static final Logger	LOGGER	= LoggerFactory.getLogger(WebUtil.class);

	private WebUtil() {

	}

	/**
	 * Description: get the current request bound to current thread.
	 *
	 * @return
	 */
	public static HttpServletRequest getThreadRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	/**
	 * Description:.
	 *
	 * @return
	 */
	public static HttpSession getThreadSession() {
		return getThreadRequest().getSession(true);
	}

	public static User getSessionUser() {
		HttpSession session = getThreadRequest().getSession(true);

		User user = (User) session.getAttribute(RightmrgGlobe.SESSION_USER_KEY);
		return user;
	}

	public static String getSessionUserName() {
		if(null==getSessionUser()){
			return null;
		}
		return getSessionUser().getUserName();
	}

	/**
	 * Description: determine whether current request is sent via AJAX.
	 *
	 * @return
	 */
	public static boolean isAjaxRequest() {
		return isAjaxRequest(getThreadRequest());
	}

	/**
	 * Description: determine whether given request is sent via AJAX.
	 *
	 * @param request
	 * @return
	 */
	public static boolean isAjaxRequest(HttpServletRequest request) {
		String requestedWith = request.getHeader("X-Requested-With");
		return requestedWith != null ? "XMLHttpRequest".equals(requestedWith) : false;
	}

	/**
	 * Description: get the full URL for a relative path.
	 *
	 * @param path
	 * @return
	 */
	public static String getFullUrlBasedOn(String path) {
		StringBuilder targetUrl = new StringBuilder();
		if (path.startsWith("/")) {
			// Do not apply context path to relative URLs.
			targetUrl.append(getThreadRequest().getContextPath());
		}
		targetUrl.append(path);
		return targetUrl.toString();
	}

	/**
	 * Description: get the full URL for a relative path.
	 *
	 * @return
	 */
	public static String getContextPath() {
		StringBuilder targetUrl = new StringBuilder();
		// Do not apply context path to relative URLs.
		targetUrl.append(getThreadRequest().getContextPath());
		return targetUrl.toString();
	}


	public static HashSet<Integer> getActSet() {
		HashSet<Integer> actSet  = (HashSet<Integer>) getThreadSession().getAttribute(RightmrgGlobe.SESSION_USER_FUNS);
		return actSet;
	}
	
	public static boolean havaAct(int act) {
		HashSet<Integer> actSet = getActSet();
		if (null != actSet && actSet.contains(act)) {
			return true;
		}
		return false;
	}

	public static boolean havaCol(int col) {
		ArrayList<Integer> colSet = (ArrayList<Integer>) getThreadSession().getAttribute(RightmrgGlobe.SESSION_DEPT_COLUMNS);
		if (null != colSet && colSet.contains(col)) {
			return true;
		}
		return false;
	}

	public static String getSessionId() {
		HttpSession session = getThreadSession();
		if (null == session) {
			return null;
		}
		return session.getId().toString();
	}

	public static ServletContext getServletContext() {
		WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
		ServletContext servletContext = webApplicationContext.getServletContext();

		return servletContext;
	}

	/**
	 * Description: 获取客户端ip.
	 *
	 * @return
	 */
	public static String getRemoteAddress(HttpServletRequest request) {
//		String ip = request.getHeader("x-forwarded-for");
//		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//			ip = request.getRemoteAddr();
//		}
//		return ip;
		String ip = request.getHeader("x-forwarded-for"); 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("Proxy-Client-IP"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("WL-Proxy-Client-IP"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("HTTP_CLIENT_IP"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("HTTP_X_FORWARDED_FOR"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getRemoteAddr(); 
	    } 
	    return ip; 
	}

	/**
	 * Description: 通过命令nbtstat -a ip来获得该ip相对应的mac地址.
	 * 
	 * @param ip
	 * @return String MAC地址
	 */
	public static String getMACAddress(String ip) {
		String str = "";
		String macAddress = "";
		try {
			Process p = Runtime.getRuntime().exec("nbtstat -a " + ip);
			InputStreamReader ir = new InputStreamReader(p.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);
			for (int i = 1; i < 100; i++) {
				str = input.readLine();
				if (str != null && str.indexOf("MAC") > 1) {
					// if (str.indexOf("MAC Address") > 1) {
					macAddress = str.substring(str.indexOf("=") + 2, str.length());
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace(System.out);
		}
		return macAddress;
	}

	// 项目管理的数据权限
	@SuppressWarnings("unchecked")
	public static Map<String, Object> getUserRight() {
		return (Map<String, Object>) getThreadSession().getAttribute(RightmrgGlobe.SESSION_USER_RIGHT);
	}
}
